package com.huanglj.himalaya.activitys;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import com.huanglj.himalaya.R;
import com.huanglj.himalaya.adapters.PlayerTrackPagerAdapter;
import com.huanglj.himalaya.base.BaseActivity;
import com.huanglj.himalaya.interfaces.IPlayerCallBack;
import com.huanglj.himalaya.presenters.PlayerPresenter;
import com.huanglj.himalaya.utils.LogUtil;
import com.huanglj.himalaya.views.PobWindow;
import com.huanglj.himalaya.views.RotateImageView;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

public class PlayerActivity extends BaseActivity implements View.OnClickListener, IPlayerCallBack, ViewPager.OnPageChangeListener {
    private static final String TAG = "PlayerActivity";
    private PlayerPresenter mPlayerPresenter;
    private ImageView mPlayOrPause;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mDurationTime;
    private TextView mCurrentTime;
    private SeekBar mSeekBar;
    private int currentProgress = 0;
    private boolean isUserTouch = false;
    private ImageView mPlayPre;
    private ImageView mPlayNext;
    private TextView mTrackView;
    private ViewPager mTrackImage;
    private PlayerTrackPagerAdapter mPagerAdapter;
    private boolean isUserTouchPage = false;
    private ImageView mPlayModeBtn;
    private boolean isPlay = false;
    private XmPlayListControl.PlayMode mCurrentMode = PLAY_MODEL_LIST;
    RotateImageView mRectImageView;
    private static Map<XmPlayListControl.PlayMode,XmPlayListControl.PlayMode> playRules = new HashMap<>();
    private boolean isReverse = false;


    static {
        playRules.put(PLAY_MODEL_LIST,PLAY_MODEL_LIST_LOOP);
        playRules.put(PLAY_MODEL_LIST_LOOP,PLAY_MODEL_RANDOM);
        playRules.put(PLAY_MODEL_RANDOM,PLAY_MODEL_SINGLE_LOOP);
        playRules.put(PLAY_MODEL_SINGLE_LOOP,PLAY_MODEL_LIST);
    }

    private ImageView mPlayList;
    private PobWindow mPobWindow;
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mExitBgAnimator;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        initView();
        //注册接口监听
        mPlayerPresenter.registerViewCallBack(this);
        updatePlayState();
        //处理事件
        initEvent();
        //渐变动画
        initBgAnimation();

    }
    //进入的时候判断状态
    private void updatePlayState() {
        mPlayOrPause.setImageResource(mPlayerPresenter.isPlay() ? R.mipmap.pause_press : R.mipmap.play_press);
    }

    private void initBgAnimation() {
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f,0.8f);
        mEnterBgAnimator.setDuration(500);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });
        mExitBgAnimator = ValueAnimator.ofFloat(0.8f, 1.0f);
        mExitBgAnimator.setDuration(500);
        mExitBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mTrackView.setSelected(true);
        //设置进度监听
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    currentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isUserTouch = true;
                mPlayerPresenter.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isUserTouch = false;
                mPlayerPresenter.seekTo(currentProgress);
                mPlayerPresenter.play();
                //手离开时更新进度

            }
        });

        //设置滑动界面监听
        mTrackImage.addOnPageChangeListener(this);

        mTrackImage.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action){
                    case MotionEvent.ACTION_DOWN:
                        isUserTouchPage = true;
                        break;

                }
                return false;
            }
        });

        //设置点击后恢复原来的背景色
        mPobWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mExitBgAnimator.start();
            }
        });
        //接收PlayListAdapter传来的值，改变播放的歌曲
        mPobWindow.setOnItemClickListener(new PobWindow.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mPlayerPresenter.playByIndex(position);
            }
        });
        //接收pobWindow的切换模式接口
        mPobWindow.setOnPlayListener(new PobWindow.OnPlayListListener() {
            @Override
            public void onPlayMode() {
                switchPlayMode();
            }

            @Override
            public void onPlayOrderList() {
                mPlayerPresenter.reversePlayList();

                mPobWindow.updateOrderChange(isOrder);
                isOrder = !isOrder;
            }
        });
    }
    private boolean isOrder = false;

    private void switchPlayMode() {
        XmPlayListControl.PlayMode playMode = playRules.get(mCurrentMode);
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(playMode);
            mCurrentMode = playMode;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消接口监听
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }


    /**
     * 初始化各个控件
     */
    private void initView() {
        mPlayOrPause = findViewById(R.id.player_or_pause);
        mPlayOrPause.setOnClickListener(this);
        mDurationTime = findViewById(R.id.duration_time);
        mCurrentTime = findViewById(R.id.current_time);
        mSeekBar = findViewById(R.id.track_seek_bar);
        mPlayPre = findViewById(R.id.player_pre);
        mPlayNext = findViewById(R.id.player_next);
        mPlayPre.setOnClickListener(this);
        mPlayNext.setOnClickListener(this);
        mTrackView = findViewById(R.id.track_title);
        mTrackImage = findViewById(R.id.track_image);
        //创建适配器
        mPagerAdapter = new PlayerTrackPagerAdapter();
        mTrackImage.setAdapter(mPagerAdapter);
        mPlayModeBtn = findViewById(R.id.play_mode_switch_btn);
        mPlayModeBtn.setOnClickListener(this);
        mPlayList = findViewById(R.id.play_list);
        mPlayList.setOnClickListener(this);
        mPobWindow = new PobWindow(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //如果现在是播放状态，就暂停；如果现在是暂停状态，就播放
            case R.id.player_or_pause:
                //TODU:妈的，这逻辑我理不清了；先放着
                if(mPlayerPresenter.isPlay()){
                    mPlayerPresenter.pause();
                }else {
                    mPlayerPresenter.play();
                }
                break;
             //点击上一首下一首时，如果正在播放，停止他
            case R.id.player_pre:
                if(mPlayerPresenter.isPlay()){
                    mPlayerPresenter.stop();
                }
                mPlayerPresenter.playPrevious();
                break;
            case R.id.player_next:
                if(mPlayerPresenter.isPlay()){
                    mPlayerPresenter.stop();
                }
                mPlayerPresenter.playNext();
                break;
            case R.id.play_mode_switch_btn:
                switchPlayMode();
                break;
            case R.id.play_list:
                //TODO:需要展示播放列表
                LogUtil.d(TAG,"onClick");
                mPobWindow.showAtLocation(v, Gravity.BOTTOM,0,0);

                //点击后背景透明度做渐变处理
                mEnterBgAnimator.start();
                break;
        }
    }
    //设置背景色
    private void updateBgAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attibutes = window.getAttributes();
        attibutes.alpha = alpha;
        window.setAttributes(attibutes);
    }


    //==========================用于监听控件变化的接口 start =================================
    @Override
    public void onPlayStart() {
        //播放状态改变后，这里变成暂停按钮
        mPlayOrPause.setImageResource(R.mipmap.pause_press);
        mTrackView.setSelected(true);

    }

    @Override
    public void onPlayPause() {
        //暂停按钮改变后，变成播放按钮
        //当按钮没有没触摸是才改变状态
        if (isUserTouch == false) {
            mPlayOrPause.setImageResource(R.mipmap.play_press);
        }
        mTrackView.setSelected(false);
    }

    @Override
    public void onPlayStop() {
        mTrackView.setSelected(false);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        mPagerAdapter.setData(list);
        mPobWindow.setListData(list);
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode mode) {
        mPobWindow.updateModeChange(mode);
        switch (mode){
            case PLAY_MODEL_LIST:
                mPlayModeBtn.setImageResource(R.mipmap.sort_descending_press);
                break;
            case PLAY_MODEL_LIST_LOOP:
                mPlayModeBtn.setImageResource(R.mipmap.play_mode_loop_press);
                break;
            case PLAY_MODEL_RANDOM:
                mPlayModeBtn.setImageResource(R.mipmap.play_mode_random_press);
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                mPlayModeBtn.setImageResource(R.mipmap.play_mode_loop_one_press);
                break;
            default:
                break;

        }
    }

    @Override
    public void onProgressChange(int currentProgress, int total) {
        mSeekBar.setMax(total);
        //UI层面更新时间
        String durationTime;
        if(total > 1000 * 60 * 60){
            durationTime = mHourFormat.format(total);
        }else {
            durationTime = mMinFormat.format(total);
        }
        mDurationTime.setText(durationTime);
        String currentTime;
        if(currentProgress > 1000 * 60 * 60){
            currentTime = mHourFormat.format(currentProgress);
        }else {
            currentTime = mMinFormat.format(currentProgress);
        }
        mCurrentTime.setText(currentTime);
        //更新进度
        //计算当前进度
        if (isUserTouch == false) {
            mSeekBar.setProgress(currentProgress);
        }


    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdate(Track track,int playIndex) {
        mTrackView.setText(track.getTrackTitle());
        LogUtil.d(TAG,"playIndex: " + playIndex);

        mTrackImage.setCurrentItem(playIndex,true);

        mPobWindow.setListPosition(playIndex);
        LogUtil.d(TAG,track.getTrackTitle());
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        LogUtil.d(TAG,"position: " + position);
        if (mPlayerPresenter != null && isUserTouchPage == true) {
            mPlayerPresenter.playByIndex(position);
        }
        isUserTouchPage = false;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //==========================用于监听控件变化的接口 start =================================
}
